//
//  HomeScreenWidgets.swift
//  HomeScreenWidgets
//
//  Created by 王麒皓 on 2022/12/25.
//

import WidgetKit
import AppIntents
import SwiftUI

struct Provider: TimelineProvider {
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), classTypeString: "语文", dateString: "10:00-12:00", classString: "高一3", remainingMinute: 5, allowBLE: true)
    }
    
    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), classTypeString: "语文", dateString: "10:00-12:00", classString: "高一3", remainingMinute: 5, allowBLE: true)
        completion(entry)
    }
    
    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        //        var completed = false
        var entries: [SimpleEntry] = []
        let date = Date()
        
        if UserDefaults.standard.bool(forKey: "widget.isUpdating") {
            let classType: String = UserDefaults.standard.string(forKey: "widget.classType") ?? ""
            let startTime = UserDefaults.standard.string(forKey: "widget.startTime") ?? ""
            let name: String = UserDefaults.standard.string(forKey: "widget.name") ?? ""
            let progress = UserDefaults.standard.float(forKey: "widget.progress")
            //MARK: Things needed here
            let entry = SimpleEntry(isTooEarly: true, isUpdating: true, date: date, classTypeString: classType, dateString: startTime, classString: name, remainingMinute: Int(progress), allowBLE: true)
            entries.append(entry)
            let timeline = Timeline(entries: entries, policy: .after(Calendar.current.date(byAdding: .minute, value: 5, to: entries.last?.date ?? date)!))
            completion(timeline)
            return
        }
        
        
        // Download online data
        let classData = ClassNameData()
        classData.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
        var allClasses: [EventWithClassName] = []
        _ = classData.downloadDataByHttp {
            for _class in classData.ClassName {
                let classroom = CoreData(classNameStr: _class.name)
                classroom.IS_INTERNET_OPERATION_ALLOWED_FLAG = true
                _ = classroom.downloadDataByHttp {
                    for _event in classroom.events {
                        if _event.techer == UserDefaults(suiteName: "group.classmanager")!.string(forKey: "teacherName") && _event.state == -1 {
                            allClasses.append(EventWithClassName(_event: _event, name: _class.name, classType: classroom.classes[_event._class].name))
                        }
                    }
                }
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                if allClasses.count != 0 {
                    let sortedClass = allClasses.sorted(by: {return $0._event.start < $1._event.start})
                    var _class: EventWithClassName? = nil
                    for __class in sortedClass {
                        let remaining = Int((__class._event.start-date.timeIntervalSince1970)/60)
                        if remaining >= 0 {
                            _class = __class
                            break
                        }
                    }
                    if let _class = _class {
                        //MARK: Saving things here
                        UserDefaults.standard.setValue(_class.classType, forKey: "widget.classType")
                        UserDefaults.standard.setValue(_class._event.start.string(format: "hh.mm"), forKey: "widget.startTime")
                        UserDefaults.standard.setValue(_class.name, forKey: "widget.name")
                        
                        let remaining = Int((_class._event.start-date.timeIntervalSince1970)/60)
                        var BLEName: String? = nil
                        for i in 0..<classData.ClassName.count {
                            if classData.ClassName[i].name == _class.name {
                                BLEName = classData.ClassName[i].BLEName
                                break
                            }
                        }
                        UserDefaults.standard.setValue(BLEName, forKey: "widget.lastBLEName")
                        for t in 0...remaining {
                            let time = Calendar.current.date(byAdding: .minute, value: t, to: date)!
                            let entry = SimpleEntry(date: time, classTypeString: _class.classType, dateString: _class._event
                                .start.string(format: "hh.mm"), classString: _class.name, remainingMinute: remaining-t, allowBLE: BLEName != nil)
                            entries.append(entry)
                        }
                        if entries.count > 60 {
                            entries = []
                            let entry = SimpleEntry(isTooEarly: true, date: date, classTypeString: _class.classType, dateString: _class._event
                                .start.string(format: "hh.mm"), classString: _class.name, remainingMinute: remaining, allowBLE: BLEName != nil)
                            entries.append(entry)
                        }
                    }
                    else {
                        let entry = SimpleEntry(date: date, classTypeString: NSLocalizedString("暂无课程", comment: ""), dateString: NSLocalizedString("暂无课程", comment: ""), classString: NSLocalizedString("暂无课程", comment: ""), remainingMinute: 0, allowBLE: false)
                        entries.append(entry)
                    }
                }
                else {
                    let entry = SimpleEntry(date: date, classTypeString: NSLocalizedString("暂无课程", comment: ""), dateString: NSLocalizedString("暂无课程", comment: ""), classString: NSLocalizedString("暂无课程", comment: ""), remainingMinute: 0, allowBLE: false)
                    entries.append(entry)
                }
                print(classData, allClasses, entries)
                //                completed = true
                
                let timeline = Timeline(entries: entries, policy: .after(Calendar.current.date(byAdding: .minute, value: 5, to: entries.last?.date ?? date)!))
                print(Date(), "ok:::", UserDefaults(suiteName: "group.classmanager")?.string(forKey: "nameTester") ?? "nil")
                completion(timeline)
            }
        }
    }
}

struct EventWithClassName {
    let _event: event
    let name: String
    let classType: String
}

struct SimpleEntry: TimelineEntry {
    var isTooEarly: Bool = false
    var isUpdating: Bool = false
    
    let date: Date
    let classTypeString: String
    let dateString: String
    let classString: String
    let remainingMinute: Int
    let allowBLE: Bool
}

struct HomeScreenWidgetsEntryView : View {
    var entry: Provider.Entry
    
    //MARK: Testcodes
    var name: String = UserDefaults(suiteName: "group.classmanager")?.string(forKey: "nameTester") ?? ""
    
    @Environment(\.widgetFamily) var widgetFamily
    
    var body: some View {
        if widgetFamily == .systemSmall || widgetFamily == .systemMedium {
            ZStack {
                LinearGradient(colors: [.blue, .purple, .pink], startPoint: UnitPoint.topLeading, endPoint: UnitPoint.bottomTrailing)
                    .opacity(0.5)
                HStack(alignment: .center) {
                    VStack(alignment: .leading) {
                        Text(widgetFamily == .systemSmall ? "临近课程 \(entry.classTypeString)":"临近课程")
                            .fontWeight(.heavy)
                            .foregroundColor(.white)
                            .opacity(0.6)
                        Spacer()
                        
                        //MARK: Modified for test
                        if (entry.remainingMinute <= 5 || entry.isUpdating) && entry.dateString != "暂无课程" && entry.allowBLE {
                            Toggle("", isOn: false, intent: SignInWidget())
                                .toggleStyle(SignInToggleStyle())
//                            Button(intent: SignInWidget()) {
//                                HStack(alignment: .center) {
//                                    Image(systemName: "wave.3.backward")
//                                        .foregroundColor(.white)
//                                        .opacity(1)
//                                    Text(entry.isUpdating ? "签到中...":"立即签到")
//                                        .minimumScaleFactor(widgetFamily == .systemSmall ? 0.5:1.0)
//                                        .foregroundColor(.white)
//                                        .bold()
//                                        .opacity(1)
//                                }
//                            }
//                            .tint(.green)
//                            .disabled(entry.isUpdating)
                        } else {
                            Text("时间：")
                                .foregroundColor(.white)
                            Text(entry.dateString)
                                .fontWeight(.bold)
                                .foregroundColor(.white)
                        }
                        
                        if widgetFamily == .systemSmall && !entry.isTooEarly {
                            Text("还有\(entry.remainingMinute)分钟上课")
                                .font(.footnote)
                                .foregroundColor(.white)
                                .fontWeight(.bold)
                        }
                        Spacer()
                        
                        Text("上课班级：")
                            .foregroundColor(.white)
                        Text(entry.classString)
                            .fontWeight(.bold)
                            .foregroundColor(.white)
                        
                        if widgetFamily == .systemMedium {
                            Text("刷新时间：\(entry.date.timeIntervalSince1970.string(format: "hh.mm"))")
                                .font(.footnote)
                                .minimumScaleFactor(0.8)
                        }
                    }
                    Spacer()
                    if widgetFamily == .systemMedium {
                        VStack {
                            ZStack {
                                ProgressView(value: Float(entry.remainingMinute) > 25 ? 25:Float(entry.remainingMinute), total: 25)
                                    .progressViewStyle(CircularProgressViewStyle())
                                    .tint(.white)
                                Text(entry.classTypeString)
                                    .fontWeight(.heavy)
                                    .foregroundColor(.white)
                                    .opacity(0.6)
                            }
                            if !entry.isTooEarly {
                                Text(entry.classString == "暂无课程" ? "暂无课程":"还有\(entry.remainingMinute)分钟上课")
                            }
                        }
                        .foregroundColor(.white)
                    }
                }
                .padding()
            }
        }
        else if widgetFamily == .accessoryRectangular {
            HStack {
                VStack(alignment: .leading, spacing: 0) {
                    Text((entry.remainingMinute <= 5 && entry.dateString != "暂无课程") && entry.allowBLE ?
                         "\(entry.classString)班 \(entry.classTypeString)":"临近课程 \(entry.classTypeString)")
                        .font(.subheadline)
                        .fontWeight(.bold)
                        .minimumScaleFactor(0.1)
                    if entry.remainingMinute > 5 || entry.dateString == "暂无课程" || !entry.allowBLE {
                        Text("班级：\(entry.classString)")
                            .font(.subheadline)
                            .fontWeight(.bold)
                            .minimumScaleFactor(0.8)
                    }
                    
                    HStack {
                        Text("时间：\(entry.dateString)")
                            .font(.subheadline)
                            .fontWeight(.bold)
                            .minimumScaleFactor(0.8)
                        if (entry.remainingMinute <= 5 || entry.isUpdating) && entry.dateString != "暂无课程" && entry.allowBLE {
                            Toggle("", isOn: false, intent: SignInWidget())
                                .toggleStyle(SignInToggleStyle())
//                            Button(intent: SignInWidget()) {
//                                HStack(alignment: .center) {
//                                    if !entry.isUpdating {
//                                        Image(systemName: "wave.3.backward")
//                                            .foregroundColor(.white)
//                                            .opacity(1)
//                                            .imageScale(.small)
//                                    }
//                                    Text(entry.isUpdating ? "签到中...":"签到")
//                                        .minimumScaleFactor(0.5)
//                                        .bold()
//                                }
//                            }
//                            .tint(.green)
                        }
                    }
                    
                    if entry.remainingMinute > 5 || entry.dateString == "暂无课程" || !entry.allowBLE {
                        if !entry.isTooEarly {
                            HStack(spacing: 0) {
                                Text("还有\(entry.remainingMinute)分钟")
                                    .fontWeight(.bold)
                                    .padding(.trailing)
                                    .minimumScaleFactor(0.1)
                                ProgressView(value: Double(entry.remainingMinute) > 25 ? 25:Double(entry.remainingMinute), total: 25)
                            }
                        }
                    }
                }
                Spacer()
            }
        }
    }
}

struct HomeScreenWidgets: Widget {
    let kind: String = "HomeScreenWidgets"
    
    var body: some WidgetConfiguration {
        let config = StaticConfiguration(kind: kind, provider: Provider()) { entry in
            HomeScreenWidgetsEntryView(entry: entry)
                .containerBackground(.white, for: .widget)
        }
            .configurationDisplayName("课程概览")
            .description("快速查看临近课程")
            .supportedFamilies([.systemSmall, .systemMedium, .accessoryRectangular])
        return config.contentMarginsDisabled()
    }
}
